package com.atguigu.cloud.mygateway;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author bairimengchang
 * @version 1.0
 * @project cloud2024
 * @description 自定义断言
 * 需求：自定义配置会员等级userType，并根据会员等级进行路由访问控制
 * @date 2024/10/27
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {

    // 无参构造方法，必须的
    public MyRoutePredicateFactory() {
        super(MyRoutePredicateFactory.Config.class);
    }

    // 静态内部类，这个就是断言的规则配置
    @Setter
    @Getter
    @Validated
    public static class Config {

        @NotEmpty
        private String userType;
    }

    // 支持快捷写法
    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userType");
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyRoutePredicateFactory.Config config) {

        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");
                if (userType == null) {
                    // 没有这个参数就不允许访问
                    return false;
                }
                // 忽略大小写比较参数，如果传来的参数与yml配置里的一致就允许访问
                // http://192.168.127.52:9527/pay/gateway/get/1?userType=diamond
                return userType.equalsIgnoreCase(config.getUserType());
            }

        };
    }
}
